﻿using ConfExpert.Forms.Base;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraRichEdit.API.Native;
using DevTeam;
using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace ConfExpert.Araclar
{
    public partial class Attachments : XForm
    {
        public Attachments()
        {
            InitializeComponent();

            TAM.PriceListTableAdapter = new ConfExpert.Datasets.MyDataTableAdapters.PriceListTableAdapter();
            TAM.InfoTableAdapter = new ConfExpert.Datasets.MyDataTableAdapters.InfoTableAdapter();
        }

        string tur;
        public Attachments(string tur)
            : this()
        {
            this.tur = tur;
            this.Text = tur;
        }

        BindingSource bs;
        private void Attachments_Load(object sender, EventArgs e)
        {
            bs = new BindingSource(ds, tur);
            InitGridView(gridView1, bs);
            richEditControl1.DataBindings.Add("Text", bs, "Notes");
            gridView1.MakeColumnInvisible("DosyaId", "UserId");
            GetDetails(tur, "GetAttachments", WhoAmI, tur);

            //gridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

            //TODO: TIP: If you want to force focus to newly added rows, try setting the GridView's OptionsNavigation.AutoFocusNewRow property to True.
            AddBsToList(bs);

            //gridView1.OptionsBehavior.Editable = false;
            //gridView1.DragObjectDrop += new DevExpress.XtraGrid.Views.Base.DragObjectDropEventHandler(gridView1_DragObjectDrop);
            this.DragEnter += new DragEventHandler(Attachments_DragEnter);
            this.DragDrop += new DragEventHandler(Attachments_DragDrop);
            gridView1.Click += new EventHandler(gridView1_Click);

            GridManager gm = GridManager.GetManager(gridView1);
            gm.GridMenu.AddMenu("Aç", Ac);

            if (ytk(114))
            {
                gm.GridMenu.AddMenu("Değiştir", Degistir);
                gm.GridMenu.AddMenu("Sil", Sil);

                this.AllowDrop = true;
            }
            else
            {
                btnKaydet.Visibility =
                btnNewRow.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                gridView1.ShowingEditor += gridView1_ShowingEditor;
            }

            btnNewRow.ItemClick += btnNewRow_ItemClick;
            btnKaydet.ItemClick += btnKaydet_ItemClick;

            gridView1.RowCellStyle += new DevExpress.XtraGrid.Views.Grid.RowCellStyleEventHandler(gridView1_RowCellStyle);
            gridView1.BestFitColumns();
            //gridView1.ShowFindPanel();

            gridView1.MakeColumnInvisible("Notes");
            /*
            gridView1.Columns["Notes"].Width = 400;
            gridView1.Columns["Notes"].ColumnEdit = new RepositoryItemMemoExEdit();

            ((RepositoryItemMemoExEdit)gridView1.Columns["Notes"].ColumnEdit).ShowIcon = false;
            ((RepositoryItemMemoExEdit)gridView1.Columns["Notes"].ColumnEdit).PopupFormMinSize = new Size(500, 300);
             */
            //splitContainerControl1.SizeChanged += MySizeChanged;

            richEditControl1.Document.DefaultParagraphProperties.Alignment = ParagraphAlignment.Justify;
            richEditControl1.Document.DefaultCharacterProperties.FontName = "Calibri";
            bs.CurrentChanged += bs_CurrentChanged;
        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Save();
        }

        void btnNewRow_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.AddNewRow();
        }

        void bs_CurrentChanged(object sender, EventArgs e)
        {
            richEditControl1.Document.DefaultCharacterProperties.FontSize = 16;
        }


        void gridView1_Click(object sender, EventArgs e)
        {
            GridHitInfo hi = gridView1.CalcHitInfo(gridControl1.PointToClient(MousePosition));
            if ((hi.InRow || hi.InRowCell) && gridView1.FocusedRowHandle > -1)
            {
                txtInfo.Caption = gridView1.GetFocusedRowCellDisplayText("Adi");
                if (gridView1.FocusedColumn.FieldName == "Ext")
                {
                    //Guid ID = (Guid)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "DosyaId");
                    int DosyaId = intParse(gridView1.GetFocusedRowCellValue("DosyaId"));
                    if (DosyaId > 0)
                    {
                        DataTable t = Session.DataManager.ExecuteDataTable("GetDoc", DosyaId);

                        //GetDetails("Attachment", "GetAttachment", DosyaId, string.Empty);
                        //string FileName  = (string)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FileName");
                        //ByteArrayToFile(FileName, ds.Dosya.FindByDosyaId(DosyaId).BLOB);
                        FileManager.RunTempFile(t.Rows[0]["DosyaAdi"].ToString(), t.Rows[0]["BLOB"] as byte[]);
                    }
                }
            }
        }

        void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            GridView view = sender as GridView;

            if (e.RowHandle == view.FocusedRowHandle)
                e.Appearance.BackColor = Color.YellowGreen; // SystemColors.ControlDark;
            else
                e.Appearance.Combine((e.RowHandle & 1) != 0 ? view.Appearance.EvenRow : view.Appearance.OddRow);

            if (e.Column.FieldName == "Ext")
            {
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                e.Appearance.ForeColor = Color.DarkOrchid;
            }
        }


        void Attachments_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

            foreach (string file in files)
            {
                FileInfo fi = new FileInfo(file);

                byte[] bArr = FileManager.Read(fi.FullName);

                GetDetails(tur, "AddDoc", 0, fi.Name, fi.Extension, bArr, WhoAmI, tur, 0);
                Notify("'" + fi.Name + "' eklendi.");
            }
            gridView1.BestFitColumns();
            gridView1.Columns["Notes"].Width = 400;
        }

        void Attachments_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
                e.Effect = DragDropEffects.All;
        }



        void gridView1_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //if (gvListe.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
            e.Cancel = (intParse(gridView1.GetFocusedRowCellValue("UserId")) != WhoAmI);
            //e.Cancel = (gvCounting.GetRowCellValue(gvCounting.FocusedRowHandle, "isReadOnly").ToString() == bool.TrueString);
        }


        private void Degistir(object sender, EventArgs e)
        {
            if (gridView1.GetFocusedRowCellValue("DosyaId") != null)
            {
                int DosyaId = intParse(gridView1.GetFocusedRowCellValue("DosyaId"));
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (openFileDialog1.OpenFile() != null)
                        {
                            FileInfo fi = new FileInfo(openFileDialog1.FileName);

                            byte[] bArr = FileManager.Read(openFileDialog1.FileName);
                            GetDetails(tur, "UpdDoc", DosyaId, fi.Name, fi.Extension, bArr, WhoAmI, tur, 0);
                            gridView1.BestFitColumns();
                            Notify("'" + fi.Name + "' güncellendi.");
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        private void Sil(object sender, EventArgs e)
        {
            if (gridView1.GetFocusedRowCellValue("DosyaId") != null)
                if (XtraMessageBox.Show("Emin misiniz?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    int DosyaId = intParse(gridView1.GetFocusedRowCellValue("DosyaId"));

                    ExecuteNonQuery("DelDoc", DosyaId);

                    gridView1.DeleteRow(gridView1.FocusedRowHandle);
                    Save();
                    Notify("Dosya silindi.");
                }
        }

        private void Ac(object sender, EventArgs e)
        {
            gridView1_Click(null, null);
        }


    }
}